<?php

namespace App\Server\Task;

use App\Model\Friend\FriendBean;
use App\Model\Message\MessageBean;
use App\Model\Message\MessageModel;
use App\Msg\MsgCode;
use App\Msg\MsgInfo;
use App\Utility\Common;
use EasySwoole\Core\Http\Message\Status;
class PassFriendTask extends AbstractTask {
	
	/**
	 * 执行任务的内容
	 *
	 * @param mixed $taskData
	 *        	任务数据
	 * @param int $taskId
	 *        	执行任务的task编号
	 * @param int $fromWorkerId
	 *        	派发任务的worker进程号
	 * @author : evalor <master@evalor.cn>
	 */
	function run($taskData, $taskId, $fromWorkerId) {
		
		// 需要注意的是task编号并不是绝对唯一
		// 每个worker进程的编号都是从0开始
		// 所以 $fromWorkerId + $taskId 才是绝度唯一的编号
		// !!! 任务完成需要 return 结果
		$friendinfo = $taskData ['friendinfo'];
		$myinfo = $taskData ['userinfo'];
		$tofd = $taskData ['tofd'];
		$myfd = $taskData ['myfd'];
		$id = $taskData ['id'];
		$status = $taskData ['status'];
		(new Common ())->E ( "PassFriendTask----------->".$taskData ['userinfo'] ['phone'] . "处理好友申请异步" );
		
		// 生产一个消息存入数据库
		
		$message = new MessageBean ();
		$message->setId ( $id. $taskId . $fromWorkerId );
		$message->setAddtime ( time () );
		$message->setFromid ( $myinfo ['uid'] );
		$message->setUid ( $friendinfo ['uid'] );
		
		if ($status == FriendBean::ADD_FRIEND_PASS) {
			$sendMsg = $myinfo ['uid'] . "同意了你的好友申请";
			$message->setType ( MessageBean::ADD_FRIEND_PASS_TYPE );
		}
		if ($status == FriendBean::ADD_FRIEND_REFUSE) {
			$sendMsg = $myinfo ['uid'] . "拒绝了你的好友申请";
			$message->setType ( MessageBean::ADD_FRIEND_REFUSE_TYPE );
		}
		
		$message->setContent ( $sendMsg );
		$add = new MessageModel ();
		$flag2 = $add->addMessage ( $message );
		if ($flag2) {
			(new Common ())->E ( "异步 消息添加入库  success" );
		} else {
			(new Common ())->E ( "异步 消息添加入库  error " . $add->getLastError () );
		}
		
		$msg = (new Common ())->dealMessage ( MsgCode::MESSAGE_PASS_SUCCESS, $message, MsgInfo::SYSTEM_MSG_TITLE );
		(new Common ())->pushMessage ( $tofd, $msg );
		
		return $taskId . $fromWorkerId;
	}
	
	/**
	 * 任务执行完的回调
	 *
	 * @param mixed $result
	 *        	任务执行完成返回的结果
	 * @param int $task_id
	 *        	执行任务的task编号
	 * @author : evalor <master@evalor.cn>
	 */
	function finish($result, $task_id) {
		// 任务执行完的处理
		echo "finish :" . $result . PHP_EOL;
	}
}